import sqlite3
import os
uuid_len = 40
def create_database(db_path:str='db.sql',check_exist:bool=True,init:bool=False):
    exist = False
    if check_exist:
        exist = os.path.exists(db_path)
    if not exist:
        print(f"db not exist in path {os.path.abspath(db_path)}, ready to create it.")
    db = sqlite3.connect(db_path)
    if (not exist) and init:
        cursor = db.cursor()
        cursor.execute("drop table if exists Device")
        cursor.execute(f'''
            create table Device(
                id  char({uuid_len}) primary key not null,
                name varchar(20) 
            )
        ''')
        cursor.execute("drop table if exists net4")
        cursor.execute(f'''
            create table net4(
                id char({uuid_len}) primary key not null,
                hostid char({uuid_len}) not null ,
                ip_address varchar(20)
            )
        ''')
        cursor.execute("drop table if exists net6")
        cursor.execute(f'''
            create table net6(
                id char({uuid_len}) primary key not null,
                hostid char({uuid_len}) not null,
                ip_address varchar(20)
            )
        ''')
        cursor.execute("drop table if exists node")
        cursor.execute(f'''
            create table node(
                id char({uuid_len}) not null primary key ,
                device_id char({uuid_len}) not null ,
                port int not null 
            )
        ''')
        cursor.execute("drop table if exists listen")
        cursor.execute(f'''
            create table listen(
                id char({uuid_len}) primary key,
                net_id char({uuid_len}) not null,
                type int not null,
                port int not null
            )
        ''')
        cursor.execute("drop table if exists Folder")
        cursor.execute(f'''
            create table Folder(
                id              char({uuid_len}) primary key not null,
                belonging_node  char(32) not null,
                filename        varchar(20) not null,
                size_d          integer not null,
                size            integer not null,
                files_md5_d     char(32) not null,
                files_md5       char(32) not null,
                modified        timestamp not null,
                last_check      timestamp not null 
            )
        ''')
        print("done")



if __name__ == '__main__':
    create_database('../db.sql',check_exist=False,init=True)